package cn.itcast.bos.web.action;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;

import cn.itcast.bos.constant.Constants;
import cn.itcast.bos.utils.MailUtils;
import cn.itcast.crm.domain.Customer;
@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class CustomerAction extends BaseAction<Customer> {

	//注入jmsTemplate
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;
	
	@Action(value="customer_sendSms")
	public String sendSms(){
		//手机保存在customer对象中
		//随机生成4位数验证码,并存入session中
		String randomCode = RandomStringUtils.randomNumeric(4);
		ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(), randomCode);
		System.out.println("生成的验证码为:"+randomCode);
		
		//编辑短信内容
		final String msg="尊敬的用户,你好,本次验证码为:"+randomCode+",服务电话:4006184000";
		
		//调用MQ服务,发送一条消息(相当于短信生产者)
		jmsTemplate.send("bos_sms", new MessageCreator() {
			
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", model.getTelephone());
				mapMessage.setString("msg", msg);
				return mapMessage;
			}
		});
		return NONE;
	}
	
	//属性驱动
	private String checkcode;

	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}
	
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	
	@Action(value="customer_regist",results={@Result(name="success",location="signup-success.html",type="redirect"),
	@Result(name="input",type="redirect",location="signup.html")})
	public String regist(){
		//先校验验证码是否正确,不正确跳回注册界面
		//从session中获取之前存入的验证码
		String checkcodeSession=(String) ServletActionContext.getRequest().getSession().getAttribute(model.getTelephone());
		if(checkcodeSession==null||!checkcodeSession.equals(checkcode)){
			//验证码错误
			System.out.println("验证码有误!");
			return INPUT;
		}
		//调用webService,连接crm保存客户信息
		WebClient.create("http://localhost:9002/crm_management/services/customerService/customer")
		.type(MediaType.APPLICATION_JSON).post(model);
		
		System.out.println("注册成功!");
		
		//发送一封激活邮件
		String activecode=RandomStringUtils.randomNumeric(32);
		//将激活码保存到redis中,并设置有效时长为24小时
		redisTemplate.opsForValue().set(model.getTelephone(), activecode, 24, TimeUnit.HOURS);
		
		//编辑邮件信息,并调用mailUtils发送邮件
		String content="尊敬的用户您好,请于24小时内进行邮箱的绑定,点击下面地址完成绑定:"
				+ "<br/><a href='"+MailUtils.activeUrl+"?telephone="+model.getTelephone()
				+"&activecode="+activecode+"'>速运快递邮箱绑定地址</a>";
		
		MailUtils.sendMail("速运快递邮箱激活", content, model.getEmail());
		
		return SUCCESS;
	}
	
	//属性注入邮箱激活码
	private String activecode;

	public void setActivecode(String activecode) {
		this.activecode = activecode;
	}
	
	//邮箱验证操作
	@Action(value="customer_activeMail")
	public void activeMail() throws IOException{
		//解决乱码问题
		ServletActionContext.getResponse().setContentType("text/html; charset=UTF-8");
		//从redis中取出激活码
		String activecodeRedis = redisTemplate.opsForValue().get(model.getTelephone());
		
		//判断激活码是否有效
		if(activecodeRedis==null||!activecodeRedis.equals(activecode)){
			//激活码无效
			ServletActionContext.getResponse().getWriter().println("激活码无效,请登录系统重新绑定邮箱");
		}else{
			//激活码有效
			//防止重复绑定,调用crm_management查询客户信息是否已绑定
			Customer customer=WebClient.create("http://localhost:9002/crm_management/services/customerService/customer/telephone/"
					+ model.getTelephone()).accept(MediaType.APPLICATION_JSON).get(Customer.class);
			
			if(customer.getType()==null||customer.getType()!=1){
				//该客户没有绑定邮箱,调用crm_management进行邮箱绑定操作
				WebClient.create("http://localhost:9002/crm_management/services/customerService/customer/updatetype/"
						+ model.getTelephone()).get();
				
				ServletActionContext.getResponse().getWriter().write("邮箱绑定成功!");
			}else{
				//已绑定过
				ServletActionContext.getResponse().getWriter().write("邮箱已绑定过,无需重复绑定!");
			}
			//删除redis中的激活码
			redisTemplate.delete(model.getTelephone());
		}
	}
	
	//客户登录
	@Action(value="customer_login",results={@Result(name="login",type="redirect",location="login.html"),
			@Result(name="success",type="redirect",location="index.html#/myhome")})
	public String login(){
		System.out.println(model.getTelephone()+"----"+model.getPassword());
		Customer customer = WebClient.create(Constants.CRM_MANAGEMENT_URL+"/services/customerService/customer/login?telephone="
				+model.getTelephone()+"&password="+model.getPassword())
		.accept(MediaType.APPLICATION_JSON).get(Customer.class);
		
		if(customer==null){
			//登录失败
			return LOGIN;
		}else{
			//登陆成功,将客户存入session中
			ServletActionContext.getRequest().getSession().setAttribute("customer", customer);
			return SUCCESS;
		}
	}
	
}
